package com.wuchengdong.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuchengdong.web.extend.utils.R;
import com.wuchengdong.web.pojo.Order;
import com.wuchengdong.web.pojo.Payment;
import com.wuchengdong.web.pojo.Review;
import com.wuchengdong.web.pojo.dto.OrderDTO;
import com.wuchengdong.web.service.AppointmentService;
import com.wuchengdong.web.service.OrderService;
import com.wuchengdong.web.service.PaymentService;
import com.wuchengdong.web.service.ReviewService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
@Api(tags = "订单管理(基础增删改查，业务流设计在预约Controller中)")
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    AppointmentService appointmentService;
    @Autowired
    PaymentService paymentService;
    @Autowired
    ReviewService reviewService;

    @GetMapping
    public R<List<Order>> getAll() {
        return R.success(orderService.list());
    }

    @GetMapping("/getByUserId")
    public R<List<OrderDTO>> getByUserId(Integer userId) {
        List<OrderDTO> result = new ArrayList<>();
        List<Order> orderList = orderService.list(
                new LambdaQueryWrapper<Order>()
                        .eq(Order::getUserId, userId)
        );
        for (Order order : orderList) {
            OrderDTO orderDTO = new OrderDTO(order);
            orderDTO.setAppointment(appointmentService.getById(order.getAppointmentId()));
            orderDTO.setPayments(paymentService.list(
                    new LambdaQueryWrapper<Payment>().eq(Payment::getOrderId, order.getId())
            ));
            Review review = reviewService.getOne(
                    new LambdaQueryWrapper<Review>()
                            .eq(Review::getUserId, userId)
                            .eq(Review::getAppointmentId, order.getAppointmentId())
            );
            orderDTO.setReview(review);
            result.add(orderDTO);
        }

        return R.success(result);
    }

    @PostMapping
    public R<String> save(Order order) {
        orderService.save(order);
        return R.success("添加成功");
    }

    @DeleteMapping
    public R<String> delete(Order order) {
        orderService.removeById(order.getId());
        return R.success("删除成功");
    }
}
